// utils/request.js
const config = require('../config/config.js');

const request = (options) => {
  const { url, method = 'GET', data = {}, header = {} } = options;
  console.log("🟨 🟨 🟨 >>>" + url);
  console.log("🟨 🟨 🟨 请求参数:", data);

  return new Promise((resolve, reject) => {
    const fullUrl = config.baseUrl + url;
    console.log("🟨 🟨 🟨 完整请求URL:" + fullUrl);

    wx.request({
      url: fullUrl,
      method: method,
      data: data,
      header: {
        'Content-Type': 'application/json',
        ...header
      },
      timeout: config.timeout,
      success: (res) => {
        console.log("✅ 请求成功，状态码:", res.statusCode);
        console.log("✅ 响应数据:", res.data);

        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          reject(res.data);
        }
      },
      fail: (err) => {
        console.error('❌ 请求失败:', err);
        wx.showToast({
          title: '网络连接失败',
          icon: 'none'
        });
        reject(err);
      }
    });
  });
};

// 快捷方法
const get = (url, data = {}) => request({ url, method: 'GET', data });
const post = (url, data = {}) => request({ url, method: 'POST', data });
const put = (url, data = {}) => request({ url, method: 'PUT', data });
const del = (url, data = {}) => request({ url, method: 'DELETE', data });

module.exports = {
  request,
  get,
  post, 
  put,
  del
};